//用户相关全局通用方法和数据
import { login, logout, getInfo } from '@/api/login'
import { thirdLogin } from '@/api/system/thirdAuth'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  //访问令牌
  token: getToken(),
  //用户ID
  userId: '',
  //用户所有信息
  userInfo: '',
  //用户头像
  avatar: '',
  //用户角色
  roles: [],
  //用户权限
  permissions: []
}

//mutations是Vuex中唯一允许更新应用状态的函数，是同步函数
const mutations = {
  /**
   * 设置用户访问令牌
   * @param state
   * @param token
   * @constructor
   */
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  /**
   * 设置用户名称
   * @param state
   * @param userId
   * @constructor
   */
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  /**
   * 设置用户名称
   * @param state
   * @param user
   * @constructor
   */
  SET_USER_INFO: (state, user) => {
    state.userInfo = user
  },
  /**
   * 设置用户头像
   * @param state
   * @param avatar
   * @constructor
   */
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  /**
   * 设置用户角色
   * @param state
   * @param roles
   * @constructor
   */
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  /**
   * 设置用户权限
   * @param state
   * @param permissions
   * @constructor
   */
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

//actions是Vuex中处理异步操作的函数，它们不能直接修改状态，而是通过调用 mutations 来间接修改状态
const actions = {
  /**
   * 登录并保存token令牌
   * @param commit
   * @param userInfo
   * @returns {Promise<unknown>}
   * @constructor
   */
  Login({ commit }, userInfo) {
    const tenantId = userInfo.tenantId
    const username = userInfo.username.trim()
    const password = userInfo.password
    const code = userInfo.code
    const uuid = userInfo.uuid
    return new Promise((resolve, reject) => {
      login(tenantId,username, password, code, uuid).then(res => {
        setToken(res.data.token)
        commit('SET_TOKEN', res.data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 第三方账号登录
   * @param commit
   * @param data
   * @returns {Promise<unknown>}
   * @constructor
   */
  ThirdLogin({ commit }, data) {
    return new Promise((resolve, reject) => {
      thirdLogin(data).then(res => {
        setToken(res.data.token)
        commit('SET_TOKEN', res.data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 获取用户信息
   * @param commit
   * @param state
   * @returns {Promise<unknown>}
   * @constructor
   */
  GetInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(res => {
        const user = res.data.user
        const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : user.avatar;
        if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          commit('SET_ROLES', res.data.roles)
          commit('SET_PERMISSIONS', res.data.permissions)
        } else {
          commit('SET_ROLES', ['ROLE_DEFAULT'])
        }
        commit('SET_USERID', user.userId)
        commit('SET_USER_INFO', user)
        commit('SET_AVATAR', avatar)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 退出系统
   * @param commit
   * @param state
   * @returns {Promise<unknown>}
   * @constructor
   */
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 前端登出
   * @param commit
   * @returns {Promise<unknown>}
   * @constructor
   */
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  // 必须加模块名前缀
  namespaced: true,
  state,
  mutations,
  actions
}
